package com.xiaoyun.advicetemplate.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoyun.advicetemplate.annotation.ResultAdvice;
import com.xiaoyun.advicetemplate.config.Constant;
import com.xiaoyun.advicetemplate.utils.AesEncryptUtils;
import com.xiaoyun.advicetemplate.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author monkey
 * @desc 返回数据加密
 * @date 2018/10/25 20:17
 */
@ControllerAdvice
@Slf4j
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice {

    @Autowired
    private  AesEncryptUtils aesEncryptUtils;


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //获取注解配置的包含和去除字段
        //出参是否需要加密
        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ResultAdvice resultAdvice = (ResultAdvice) servletRequest.getAttribute(Constant.HAS_RESULT_ADVICE);
        if (resultAdvice != null) {
            boolean encode = resultAdvice.outEncode();
            if (encode) {
                log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
                    return Result.ok(aesEncryptUtils.encrypt(result));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常：" + e.getMessage());
                }
            }
        }
        return Result.ok(body);
    }
}